﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using VitCode.BaseDataPageCreator;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;
using CRS.Web;
using CRS.Web.BaseData.Helper;
using VitCode.Web.UI;
using VitCode.Web.UI.ExcelFileGenerator;

namespace CRS.Web.BaseData
{
    public partial class DataImportor : VcPage
    {
        PermissionManager m_PermissionManger = new PermissionManager();

        private string SettingXmlPath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory + "Setting\\BaseImportSet.xml"; }
        }

        private AbstractImportor Importor
        {
            get { return (AbstractImportor) Session["Importor"]; }
            set { Session["Importor"] = value; }
        }

        private ErrorResult ErrorMessageResult
        {
            get
            {
                if (Session["ErrorMessageResult"] == null)
                {
                    return new ErrorResult();
                }
                return (ErrorResult) Session["ErrorMessageResult"];
            }
            set { Session["ErrorMessageResult"] = value; }
        }

        private DataTable ErrorDataResult
        {
            get
            {
                if (Session["ErrorDataResult"] == null)
                {
                    return new DataTable();
                }
                return (DataTable) Session["ErrorDataResult"];
            }
            set { Session["ErrorDataResult"] = value; }
        }

        private object BindErrorMessages()
        {
            return ErrorMessageResult;
        }

        private object BindErrorData()
        {
            if (cbContainErrMsg.Checked && ErrorDataResult != null && ErrorMessageResult != null
                && ErrorDataResult.Rows.Count > 0 && ErrorMessageResult.Rows.Count > 0
                && ErrorDataResult.Rows.Count == ErrorMessageResult.Rows.Count)
            {
                DataTable dt = null;

                for (int i = 0; i < ErrorDataResult.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        dt = ErrorDataResult.Clone();
                        for (int k = 0; k < ErrorMessageResult.Columns.Count; k++)
                            dt.Columns.Add(ErrorMessageResult.Columns[k].ColumnName);
                    }
                    int sourcedColAmount = ErrorDataResult.Columns.Count;
                    var objs = new object[dt.Columns.Count];
                    ErrorDataResult.Rows[i].ItemArray.CopyTo(objs, 0);
                    ErrorMessageResult.Rows[i].ItemArray.CopyTo(objs, sourcedColAmount);
                    DataRow r = dt.NewRow();
                    r.ItemArray = objs;
                    dt.Rows.Add(r);
                }
                return dt;
            }

            return ErrorDataResult;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
            if (String.IsNullOrEmpty(GenericContext.CurrUserCode))
            {
                Response.Redirect("../Default.aspx");
            }
            pgError.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindErrorMessages);
            pgErrorData.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindErrorData);
            btnImport.Attributes.Add("onclick",
                                     "setTimeout('document.all(\"" + btnImport.ClientID + "\").disabled=true;',10);");
            btnCheckData.Attributes.Add("onclick",
                                        "setTimeout('document.all(\"" + btnCheckData.ClientID +
                                        "\").disabled=true;',10);");
            btnOutput.Enabled = (Importor != null);
            if (!IsPostBack)
            {
                //if (!m_PermissionManger.CheckPageIsCanEdit(this))
                //{
                //    btnCheckData.Enabled = false;
                //    btnImport.Enabled = false;
                //}
                //if (!m_PermissionManger.CheckPageIsCanEdit(this))
                //    Menu1.Items[2].Enabled = false;
                Importor = null;
                ErrorMessageResult = null;
                tlbErrorData.Visible = false;
                tblBaseInfo.Visible = true;
            }
        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
           
            DateTime S_datetime = DateTime.Now;
            lblMessage.Text = "";
            try
            {
                Importor.Import(Importor.GetSourceData(true), false);

                pgError.Visible = false;
                ErrorDataResult = null;
                ErrorMessageResult = null;

                DateTime F_Datetime = DateTime.Now;
                TimeSpan showtime = F_Datetime - S_datetime;
                lblMessage.Text = "导入数据： " + Importor.InsertCount + " 条，更新数据： " + Importor.UpdateCount
                                  + " 条，导入所耗时间：" + showtime.Hours + " 时 " + showtime.Minutes + " 分 " + showtime.Seconds +
                                  " 秒";
            }
            //catch (ArgumentNullException ex)
            //{
            //    Alert.MessageBox(ex.Message);
            //}
            //catch (ArgumentOutOfRangeException ex2)
            //{
            //    Alert.MessageBox(ex2.Message);
                
            //}
            //catch (ArgumentException ex3)
            //{
            //    Alert.MessageBox(ex3.Message);
            //}
            //catch (SqlException sqlex)
            //{
            //    if (sqlex.Message.IndexOf("违反了 UNIQUE KEY 约束") > -1)
            //    {
            //        ClientScript.RegisterStartupScript(ClientScript.GetType(), "015", "系统中同时插入相同的条码，请再一次进行机校验数据");
            //    }
            //}
            //catch (OleDbException ex4)
            //{
            //    if (ex4.ErrorCode == -2147467259)
            //        ClientScript.RegisterStartupScript(ClientScript.GetType(), "014", "在上传附件中找不到表名为 “" + txtSheetName.Text + "” 的工作表");
                   
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}
            finally
            {
                Importor = null;
                btnImport.Enabled = false;
            }
           
        }

        protected void btnCheckData_Click(object sender, EventArgs e)
        {
            
            Importor = null;
            btnImport.Enabled = false;
            DateTime S_datetime = DateTime.Now;
            lblMessage.Text = "";
            if (fileSource.Value == "")
            {
                lblCheckSource.Text = "请选择导入文件";
                return;
            }

            string strFileName = fileSource.PostedFile.FileName;
            int index = strFileName.LastIndexOf("\\");
            strFileName = strFileName.Substring(index + 1, strFileName.Length - index - 1);

            if (strFileName.Substring(strFileName.Length - 4).ToLower() != ".xls")
            {
                lblMessage.Text = "请使用正确的模板文件";
                pgError.Visible = false;
                pgErrorData.Visible = false;
                return;
            }
           
            string path = Path.GetTempPath() + DateTime.Now.Ticks.ToString().Substring(5) + strFileName;
            fileSource.PostedFile.SaveAs(path);
           
            //try
            //{
                if (DemoVersionManager.IsDemo())
                {
                    //不是试用版则注释此代码
                    if (!DemoVersionManager.CheckIsDemoVersionOfImport(path, txtSheetName.Text))
                    {
                        ClientScript.RegisterStartupScript(ClientScript.GetType(), "465", "<script>alert('导入无法执行,原因是AMS试用版最大资产数不能大于60！');</script>");
                        return;
                    }
                }
              
                Importor =
                    ImportorFactory.ImportorInstance(path, txtSheetName.Text, SettingXmlPath);
                Importor.Check();
                DataTable dt = Importor.GetSourceData(true);
                int sourceDataCount = dt.Rows.Count;
                int errorDataCount = 0;
                if (Importor.ErrorMessage.Rows.Count == 0)
                {
                    pgError.Visible = false;
                    ErrorDataResult = null;
                    ErrorMessageResult = null;
                }
                else
                {
                    pgError.Visible = true;
                    pgError.SortExpression = "行号";
                    ErrorMessageResult = Importor.ErrorMessage;
                    pgError.BindGrid();
                    ErrorDataResult = Importor.GetSourceData(false);
                    errorDataCount = ErrorDataResult.Rows.Count;
                }

                DateTime F_Datetime = DateTime.Now;
                TimeSpan showtime = F_Datetime - S_datetime;
                lblMessage.Text = "正确数据： " + sourceDataCount + " 条，错误数据： " + errorDataCount + " 条，校验所耗时间：" +
                                  showtime.Hours + " 时 " +
                                  showtime.Minutes + " 分 " + showtime.Seconds + " 秒";
                btnImport.Enabled = sourceDataCount > 0;
            //}
            //catch (ArgumentNullException ex)
            //{
            //    Alert.MessageBox(ex.Message);
            //}
            //catch (ArgumentOutOfRangeException ex2)
            //{
            //    Alert.MessageBox(ex2.Message);
            //}
            //catch (ArgumentException ex3)
            //{
            //    Alert.MessageBox(ex3.Message);
            //}
            //catch (OleDbException ex4)
            //{
            //    if (ex4.ErrorCode == -2147467259)
            //        ClientScript.RegisterStartupScript(ClientScript.GetType(), "012", "在上传附件中找不到表名为 “" + txtSheetName.Text + "” 的工作表");
                  
            //}
            btnOutput.Enabled = Importor != null;
          
        }

      protected void cbContainErrMsg_CheckedChanged(object sender, EventArgs e)
        {
            pgErrorData.BindGrid();
        }

        protected void btnOutput_Click(object sender, EventArgs e)
        {
            int errorMsgColIndex = 1, errorRowNumColIndex = 0;
            if (Importor == null)
                return;
            DataTable result = null;
            DataTable source = Importor.SourceData;
            var tmpHt = new Hashtable();
            if (source == null || source.Rows.Count == 0)
            {
                Alert.MessageBox("模板中没有数据");
                return;
            }
            for (int i = 0; i < ErrorMessageResult.Rows.Count; i++)
            {
                DataRow r = ErrorMessageResult.Rows[i];
                tmpHt.Add(r[errorRowNumColIndex], r[errorMsgColIndex]);
            }
            for (int i = 0; i < source.Rows.Count; i++)
            {
                if (i == 0)
                {
                    result = ErrorDataResult.Clone();
                    result.Columns.Add("检验结果");
                    result.Columns.Add("出错信息");
                }
                var objs = new object[result.Columns.Count];
                source.Rows[i].ItemArray.CopyTo(objs, 0);
                string[] tempObjs;
                if (tmpHt.ContainsKey(i + 2))
                    tempObjs = new[] {"错误", tmpHt[i + 2].ToString()};
                else
                    tempObjs = new[] {"正确"};
                tempObjs.CopyTo(objs, source.Columns.Count);
                DataRow r = result.NewRow();
                r.ItemArray = objs;
                result.Rows.Add(r);
            }
            var exporter = new ExcelFileGenerator();
            string tempPath = exporter.ExportDataToExcelFile(result);
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition",
                                  "attachment;filename=" +
                                  HttpUtility.UrlEncode("导入模板输出(带校验信息)_" + DateTime.Now.ToString("yyyyMMdd") + ".csv"));
            Response.ContentEncoding = Encoding.Default;
            Response.ContentType = "application/ms-excel";
            Response.Clear();
            Response.WriteFile(tempPath);
            Response.End();
        }

        protected void btnShowBaseInfo_Click(object sender, EventArgs e)
        {
            tlbErrorData.Visible = false;
            tblBaseInfo.Visible = true;
            pgError.BindGrid();
        }

        protected void btnShowErrorInfo_Click(object sender, EventArgs e)
        {
            tlbErrorData.Visible = true;
            tblBaseInfo.Visible = false;
            pgErrorData.BindGrid();
        }

        protected void Menu1_MenuItemClick(object sender, System.Web.UI.WebControls.MenuEventArgs e)
        {
            int index = Int32.Parse(e.Item.Value);
            if (index == 0)
            {
                tlbErrorData.Visible = false;
                tblBaseInfo.Visible = true;
                pgError.BindGrid();
            }
            else if (index == 1)
            {
                tlbErrorData.Visible = true;
                tblBaseInfo.Visible = false;
                pgErrorData.BindGrid(); 
            }
        }
    
    }
}
